import os.path
from pprint import pprint

from django.http import HttpResponse, StreamingHttpResponse, HttpResponseBadRequest
from django.shortcuts import render
import json
# Create your views here.
from common.sql_constant_enum import case_download_corresponding, bug_download_corresponding, \
    project_download_colum_corresponding, subsys_download_colunm_correspondeing, version_download_colunm_correspondeing
from common.sql_instance_bug import construct_sql_Bug_statistics_detail
from common.sql_instance_execute import construct_sql_case_statistics_detail
from common.sql_instance_project_data import construct_project_version_statistics, construct_project_Bug_statistics, \
    construct_project_unsolved_Bug_statistics, construct_sql_get_all_subsys_by_project_id, \
    construct_sql_subsystem_detail, construct_sql_subsystem_detail_download, \
    construct_sql_subsystem_unsolved_bug_daily_increase, construct_sql_subsystem_unsolved_bug_statistics, \
    construct_version_all_iteration_version_detail_download, construct_subsystem_testtask_status_statistics, \
    construct_version_id_unsolved_bugs, construct_version_id_daily_add_bugs
from utils.cursorHandler_aiomysql import cursor
from utils.normal_simple_function import serialize_json_dumps, down_chunk_file_manager, write_download_file, \
    transfer_dict_to_str, serialize_json_date_type, transfer_list_to_str
from common.constant import file_path_case, file_path_project, file_path_bug, file_path_subsys, file_path_version


def downloadCaseStatistics(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        case_ids: tuple = request.GET.get('case_ids', None)
        if ',' in case_ids:
            case_ids = tuple(int(id.strip()) for id in case_ids.split(','))
        else:
            case_ids = [int(case_ids.strip())]
        case_condition_search_result = cursor.search_alone(
            construct_sql_case_statistics_detail(_tag_type=None,
                                                 _case_type=None,
                                                 _subsystem=None,
                                                 _milestone_verison=None,
                                                 _verison_NO=None,
                                                 _tester_name=None,
                                                 _date_range=None,
                                                 _ids=case_ids))
        # pprint(case_condition_search_result)
        column_names = tuple(case_download_corresponding[key] for key in case_condition_search_result[0].keys())
        # pprint(column_names)
        case_cloumn_values = [list(each_case.values()) for each_case in case_condition_search_result]
        # pprint(case_cloumn_values)
        write_download_file(file_path_case, column_names, case_cloumn_values)
        response = StreamingHttpResponse(down_chunk_file_manager(file_path_case))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.split(file_path_case)[1])
        return response


def downloadProjectIterationExtension(request):
    if request.method == 'GET':
        # 获取get请求带的参数

        project_ids: tuple = request.GET.get('project_ids', None)
        if ',' in project_ids:
            project_ids = tuple(int(id.strip()) for id in project_ids.split(','))
        else:
            project_ids = [int(project_ids.strip())]
        if len(project_ids) > 0:
            # 项目所有的测试单数据
            print(construct_project_version_statistics(project_ids))
            project_testtask_data: list(dict) = cursor.search_alone(construct_project_version_statistics(project_ids))
            # print('----------------------------------')
            # pprint(project_testtask_data)
            project_testtask_ids: dict = {each['id']: index for index, each in enumerate(project_testtask_data)}
            project_Bug_data: list(dict) = cursor.search_alone(construct_project_Bug_statistics(project_ids))
            # print('==================================')
            # pprint(project_Bug_data)
            project_Bug_ids: dict = {each['id']: index for index, each in enumerate(project_Bug_data)}
            project_unsolved_Bug_data: list(dict) = cursor.search_alone(
                construct_project_unsolved_Bug_statistics(project_ids))
            # print('++++++++++++++++++++++++++++++++++')
            # pprint(project_unsolved_Bug_data)
            project_unsolved_Bug_ids: dict = {each['id']: index for index, each in enumerate(project_unsolved_Bug_data)}
            json_returns = {'data': {'iteration_version_status_extension': []}}
            for project_index, project_id in enumerate(project_ids):
                # 判断测试单是否存在
                if project_id in project_testtask_ids.keys():
                    now_task = project_testtask_data[project_testtask_ids[project_id]]
                else:
                    now_task = {}
                # 判断Bug的统计结果是否存在
                if project_id in project_Bug_ids.keys():
                    now_bug = project_Bug_data[project_Bug_ids[project_id]]
                else:
                    now_bug = {}
                # 判断历史未解决Bug是否存在
                # print(project_unsolved_Bug_data)
                if project_id in project_unsolved_Bug_ids.keys():
                    now_unsolved = project_Bug_data[project_unsolved_Bug_ids[project_id]]
                else:
                    now_unsolved = {}
                # 更新测试单数据
                json_returns['data']['iteration_version_status_extension'].append(
                    {
                        "project_id": project_id,
                        "project_name": now_task.get('name', ''),
                        "iteration_num": now_task.get('total', -1),
                        "project_status_running": now_task.get('doing', -1),
                        "project_status_blocked": now_task.get('blocked', -1),
                        "project_status_done": now_task.get('done', -1),
                        "version_bug_num": {
                            "unsolved": now_bug.get('active', -1),
                            "created": now_bug.get('total', -1),
                            "solved": now_bug.get('resolved', -1),
                            "closed": now_bug.get('closed', -1)
                        },
                        "history_unsolved_bug_total": now_unsolved.get('count', 0),
                        "project_progress": round((now_task.get('done', -1) / now_task.get('total', -1) if now_task.get(
                            'total', -1) else 0) * 100, 2)  # TODO 项目进度=测试单 已完成 / 所有
                    })
            project_cloumn_values = [list(each_cloumn if type(each_cloumn) is not dict else transfer_dict_to_str(each_cloumn)
                                          for each_cloumn in each_project.values()) for each_project in json_returns['data']['iteration_version_status_extension']]
        else:
            project_cloumn_values = [[]]
        column_names = tuple(project_download_colum_corresponding.keys())
        pprint(column_names)
        write_download_file(file_path_project, column_names, project_cloumn_values)
        response = StreamingHttpResponse(down_chunk_file_manager(file_path_project))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.split(file_path_project)[1])
        return response



def downloadSubsystemIterationExtension(request):
    if request.method == 'GET':
        # 获取get请求带的参数

        subsystem_ids: tuple = request.GET.get('subsystem_ids', None)
        if ',' in subsystem_ids:
            subsystem_ids = tuple(int(id.strip()) for id in subsystem_ids.split(','))
        else:
            subsystem_ids = [int(subsystem_ids.strip())]
        subsystem_detail_rusult = [{}]
        if len(subsystem_ids) > 0:
            # 查询所有的子系统
            subsys_ids: list(dict) = subsystem_ids
            # 查询项目下的子系统的测试单的情况
            print(construct_sql_subsystem_detail_download(subsys_ids))
            subsystem_detail_rusult: list(dict) = cursor.search_alone(construct_sql_subsystem_detail_download(subsys_ids))
            # print('-------------------------', subsystem_detail_rusult)
        json_returns = {
            "data": {
                "subsystem_version_extension": [
                    {
                        "subsystem_id": each_subsys.get('subsys_id', -1),
                        "subsystem_name": each_subsys.get('pj_name', ''),
                        "online_version": each_subsys.get('task_name', ''),
                        "current_test_version": each_subsys.get('task_name', ''),
                        "plan_deadline": serialize_json_date_type(each_subsys.get('plan_deadline', '')),
                        "history_unsolved_bug_total": cursor.search_alone(
                            construct_sql_subsystem_unsolved_bug_statistics(each_subsys.get('subsys_id')))[0].get('count',
                                                                                                                  -1),
                        "this_day_bug_add": cursor.search_alone(
                            construct_sql_subsystem_unsolved_bug_daily_increase(each_subsys.get('subsys_id')))[0].get(
                            'count', -1),
                        "test_leader": each_subsys.get('testleader', ''),
                        "test_status": each_subsys.get('status', ''),
                        "remark": each_subsys.get('desc', ''),
                    } for each_subsys in subsystem_detail_rusult
                ]
            }
        }
        column_names = tuple(subsys_download_colunm_correspondeing[key] for key in
                             json_returns['data']['subsystem_version_extension'][0].keys())
        subsystem_cloumn_values = [
            list(each_cloumn for each_cloumn in each_subsystem.values()) for each_subsystem in
            json_returns['data']['subsystem_version_extension']]
        write_download_file(file_path_subsys, column_names, subsystem_cloumn_values)
        response = StreamingHttpResponse(down_chunk_file_manager(file_path_subsys))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.split(file_path_subsys)[1])
        return response


def downloadVersionIterationExtension(request):
    if request.method == 'GET':
        # 获取get请求带的参数

        version_ids: tuple = request.GET.get('version_ids', None)
        if ',' in version_ids:
            version_ids = tuple(int(id.strip()) for id in version_ids.split(','))
        else:
            version_ids = [int(version_ids.strip())]
        subsystem_detail_rusult = [{}]
        # 返回数据初始化
        json_returns = {
            "data": []}
        if len(version_ids) > 0:
            # print('-------------------------', subsystem_detail_rusult)
            for each_iteration in cursor.search_alone(construct_version_all_iteration_version_detail_download(version_ids)):
                testtask_each_status_results = \
                cursor.search_alone(construct_subsystem_testtask_status_statistics(each_iteration['version_id']))[0]
                done_status_num = testtask_each_status_results.get('done', 0)
                all_status_num = testtask_each_status_results.get('total', 1)
                # 指定的子系统获取每个月新增的Bug数据
                # 数据组装
                json_returns['data'].append(
                    {
                        "version_id": each_iteration['version_id'],
                        "version_name": each_iteration['name'],
                        "plan_cycle": [serialize_json_date_type(each_iteration['start_date']), serialize_json_date_type(each_iteration['end_date'])],
                        "plan_date_duration": each_iteration['days'],
                        "dev_leader": each_iteration['RD'],
                        "test_leader": each_iteration['QD'],
                        "unsolved_bug_total": cursor.search_alone(construct_version_id_unsolved_bugs(each_iteration['version_id']))[0].get('count', 0),
                        "this_day_bug_add": cursor.search_alone(construct_version_id_daily_add_bugs(each_iteration['version_id'], last_day=0))[0].get('count', 0),
                        "execute_progress": round((done_status_num / all_status_num if all_status_num else 1) * 100, 2),
                        "execute_status": each_iteration['status'],
                        "remark": each_iteration['desc']
                    }
                )
                versionIteration_cloumn_values = [
                    list(each_cloumn if type(each_cloumn) is not list else transfer_list_to_str(each_cloumn)
                         for each_cloumn in each_version.values()) for each_version in
                    json_returns['data']]
        else:
            versionIteration_cloumn_values = [[]]
        column_names = tuple(version_download_colunm_correspondeing[key] for key in
                             json_returns['data'][0].keys())
        write_download_file(file_path_version, column_names, versionIteration_cloumn_values)
        response = StreamingHttpResponse(down_chunk_file_manager(file_path_version))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.split(file_path_version)[1])
        return response


def downloadBugStatistics(request):
    if request.method == 'GET':
        # 获取get请求带的参数
        bug_ids: tuple = request.GET.get('Bug_ids', None)
        if ',' in bug_ids:
            bug_ids = tuple(int(id.strip()) for id in bug_ids.split(','))
        else:
            bug_ids = [int(bug_ids.strip())]
        bug_condition_search_result = cursor.search_alone(
            construct_sql_Bug_statistics_detail(
                                                _tag_type=None,
                                                _Bug_type=None,
                                                _subsystem=None,
                                                _milestone_verison=None,
                                                _verison_NO=None,
                                                _tester_name=None,
                                                _date_range=None,
                                                _resolution=None,
                                                 _ids=bug_ids))
        pprint(bug_condition_search_result)
        column_names = tuple(bug_download_corresponding[key] for key in bug_condition_search_result[0].keys())
        pprint(column_names)
        bug_cloumn_values = [list(each_bug.values()) for each_bug in bug_condition_search_result]
        pprint(bug_cloumn_values)
        write_download_file(file_path_bug, column_names, bug_cloumn_values)
        response = StreamingHttpResponse(down_chunk_file_manager(file_path_bug))
        response['Content-Type'] = 'application/octet-stream'
        response['Content-Disposition'] = 'attachment;filename="{0}"'.format(os.path.split(file_path_bug)[1])
        return response
